package com.lhz.config;


import com.lhz.model.response.ResponseObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理
 * Created by Vi
 * Date on 2019/4/17 11:07
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {

    @Value("${spring.application.name}")
    private String serviceName;

    /**
     * 服务异常
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseObject handlerException(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseObject.fail("请求错误,请稍后再试!").setService(serviceName);
    }

    //自定义异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ServiceException.class)
    public ResponseObject handleException(ServiceException e) {
        String service = e.getService() == null ? serviceName : e.getService();
        return ResponseObject.fail(e.getMessage(), e.getCode()).setService(service);
    }

}
